import api from '@/api/api'

const dic = {
  state: {
    listFormat: JSON.parse(localStorage.getItem('dicListFormat')) || {},
    mapFormat: JSON.parse(localStorage.getItem('dicMapFormat')) || {}
  },
  mutations: {
    SET_LIST_FORMAT: (state, listFormat) => {
      state.listFormat = listFormat
      localStorage.setItem('dicListFormat', JSON.stringify(listFormat))
    },
    SET_MAP_FORMAT: (state, mapFormat) => {
      state.mapFormat = mapFormat
      localStorage.setItem('dicMapFormat', JSON.stringify(mapFormat))
    }
  },
  actions: {
    getAllDic ({ commit }, params) {
      return new Promise((resolve, reject) => {
        api.getAllDic(params).then(res => {
          if (!res.success) {
            return reject(res)
          }
          let listFormat = {}
          let mapFormat = {}
          res.data && res.data.length && res.data.forEach(dic => {
            listFormat[dic.code] = dic.dicItemEntities
            let items = {}
            dic.dicItemEntities.forEach(item => {
              items[item.code] = item.name
            })
            mapFormat[dic.code] = items
          })
          commit('SET_LIST_FORMAT', listFormat)
          commit('SET_MAP_FORMAT', mapFormat)
          resolve(res)
        }).catch(err => {
          window.console && console.log(err)
          reject(err)
        })
      })
    }
  }
}

export default dic
